using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Collections.Concurrent;
using System.Text.Json;
using TaskStatus = DocumentCreationSystem.Models.TaskStatus;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 性能优化与监控服务 - 提供系统性能监控、资源优化和智能调度
    /// </summary>
    public interface IPerformanceOptimizationService
    {
        Task<SystemPerformanceMetrics> GetCurrentPerformanceMetricsAsync();
        Task<List<PerformanceAlert>> GetPerformanceAlertsAsync();
        Task<OptimizationRecommendation> GetOptimizationRecommendationsAsync();
        Task<bool> ApplyOptimizationAsync(string optimizationId);
        Task<ResourceUsageReport> GetResourceUsageReportAsync(TimeSpan period);
        Task<TaskSchedulingResult> ScheduleTaskAsync(ScheduledTask task);
        Task<List<ScheduledTask>> GetScheduledTasksAsync();
        Task<bool> CancelScheduledTaskAsync(string taskId);
        Task<PerformanceTuningResult> TunePerformanceAsync(PerformanceTuningRequest request);
        Task StartPerformanceMonitoringAsync();
        Task StopPerformanceMonitoringAsync();
    }

    public class PerformanceOptimizationService : IPerformanceOptimizationService
    {
        private readonly ILogger<PerformanceOptimizationService> _logger;
        private readonly ISystemMonitorService _systemMonitor;
        private readonly IDataStorageService _dataStorage;
        private readonly Timer? _monitoringTimer;
        private readonly ConcurrentDictionary<string, ScheduledTask> _scheduledTasks = new();
        private readonly ConcurrentQueue<PerformanceMetricSnapshot> _metricsHistory = new();
        private bool _isMonitoring = false;

        public PerformanceOptimizationService(
            ILogger<PerformanceOptimizationService> logger,
            ISystemMonitorService systemMonitor,
            IDataStorageService dataStorage)
        {
            _logger = logger;
            _systemMonitor = systemMonitor;
            _dataStorage = dataStorage;
        }

        /// <summary>
        /// 获取当前性能指标
        /// </summary>
        public async Task<SystemPerformanceMetrics> GetCurrentPerformanceMetricsAsync()
        {
            try
            {
                var systemMetrics = await _systemMonitor.GetSystemMetricsAsync();
                
                var performanceMetrics = new SystemPerformanceMetrics
                {
                    Timestamp = DateTime.Now,
                    CpuUsage = systemMetrics.CpuUsage,
                    MemoryUsage = systemMetrics.MemoryUsage,
                    DiskUsage = systemMetrics.DiskUsage,
                    NetworkUsage = systemMetrics.NetworkUsage,
                    GpuUsage = systemMetrics.GpuUsage,
                    GpuMemoryUsage = systemMetrics.GpuMemoryUsage
                };

                // 添加应用程序特定指标
                performanceMetrics.ApplicationMetrics = await GetApplicationMetricsAsync();

                // 计算性能评分
                performanceMetrics.PerformanceScore = CalculatePerformanceScore(performanceMetrics);

                return performanceMetrics;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取性能指标失败");
                return new SystemPerformanceMetrics { Timestamp = DateTime.Now };
            }
        }

        /// <summary>
        /// 获取性能警报
        /// </summary>
        public async Task<List<PerformanceAlert>> GetPerformanceAlertsAsync()
        {
            try
            {
                var alerts = new List<PerformanceAlert>();
                var currentMetrics = await GetCurrentPerformanceMetricsAsync();

                // CPU使用率警报
                if (currentMetrics.CpuUsage > 90)
                {
                    alerts.Add(new PerformanceAlert
                    {
                        Type = AlertType.HighCpuUsage,
                        Severity = AlertSeverity.Critical,
                        Message = $"CPU使用率过高: {currentMetrics.CpuUsage:F1}%",
                        Timestamp = DateTime.Now,
                        Recommendations = new List<string>
                        {
                            "关闭不必要的应用程序",
                            "检查后台进程",
                            "考虑升级硬件"
                        }
                    });
                }

                // 内存使用率警报
                if (currentMetrics.MemoryUsage > 85)
                {
                    alerts.Add(new PerformanceAlert
                    {
                        Type = AlertType.HighMemoryUsage,
                        Severity = AlertSeverity.Warning,
                        Message = $"内存使用率过高: {currentMetrics.MemoryUsage:F1}%",
                        Timestamp = DateTime.Now,
                        Recommendations = new List<string>
                        {
                            "清理内存缓存",
                            "关闭大型文档",
                            "重启应用程序"
                        }
                    });
                }

                // GPU使用率警报
                if (currentMetrics.GpuUsage > 95)
                {
                    alerts.Add(new PerformanceAlert
                    {
                        Type = AlertType.HighGpuUsage,
                        Severity = AlertSeverity.Warning,
                        Message = $"GPU使用率过高: {currentMetrics.GpuUsage:F1}%",
                        Timestamp = DateTime.Now,
                        Recommendations = new List<string>
                        {
                            "暂停AI模型训练",
                            "降低AI处理并发数",
                            "检查GPU温度"
                        }
                    });
                }

                // 磁盘空间警报
                if (currentMetrics.DiskUsage > 90)
                {
                    alerts.Add(new PerformanceAlert
                    {
                        Type = AlertType.LowDiskSpace,
                        Severity = AlertSeverity.Critical,
                        Message = $"磁盘空间不足: {currentMetrics.DiskUsage:F1}%",
                        Timestamp = DateTime.Now,
                        Recommendations = new List<string>
                        {
                            "清理临时文件",
                            "删除不需要的文档",
                            "移动文件到外部存储"
                        }
                    });
                }

                return alerts;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取性能警报失败");
                return new List<PerformanceAlert>();
            }
        }

        /// <summary>
        /// 获取优化建议
        /// </summary>
        public async Task<OptimizationRecommendation> GetOptimizationRecommendationsAsync()
        {
            try
            {
                var recommendation = new OptimizationRecommendation
                {
                    GeneratedAt = DateTime.Now
                };

                var currentMetrics = await GetCurrentPerformanceMetricsAsync();
                var historicalData = await GetHistoricalPerformanceDataAsync(TimeSpan.FromHours(24));

                // 分析性能趋势
                var trends = AnalyzePerformanceTrends(historicalData);

                // 生成优化建议
                recommendation.Recommendations = await GenerateOptimizationSuggestionsAsync(currentMetrics, trends);

                // 计算潜在收益
                recommendation.EstimatedImpact = await EstimateOptimizationImpactAsync(recommendation.Recommendations);

                return recommendation;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取优化建议失败");
                return new OptimizationRecommendation { GeneratedAt = DateTime.Now };
            }
        }

        /// <summary>
        /// 应用优化
        /// </summary>
        public async Task<bool> ApplyOptimizationAsync(string optimizationId)
        {
            try
            {
                _logger.LogInformation($"应用优化: {optimizationId}");

                switch (optimizationId)
                {
                    case "memory_cleanup":
                        return await PerformMemoryCleanupAsync();
                    case "cache_optimization":
                        return await OptimizeCacheAsync();
                    case "task_scheduling":
                        return await OptimizeTaskSchedulingAsync();
                    case "resource_allocation":
                        return await OptimizeResourceAllocationAsync();
                    default:
                        _logger.LogWarning($"未知的优化类型: {optimizationId}");
                        return false;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"应用优化失败: {optimizationId}");
                return false;
            }
        }

        /// <summary>
        /// 获取资源使用报告
        /// </summary>
        public async Task<ResourceUsageReport> GetResourceUsageReportAsync(TimeSpan period)
        {
            try
            {
                var endTime = DateTime.Now;
                var startTime = endTime.Subtract(period);

                var report = new ResourceUsageReport
                {
                    Period = period,
                    StartTime = startTime,
                    EndTime = endTime
                };

                // 获取历史数据
                var historicalData = await GetHistoricalPerformanceDataAsync(period);

                if (historicalData.Any())
                {
                    // 计算平均值
                    report.AverageCpuUsage = historicalData.Average(d => d.CpuUsage);
                    report.AverageMemoryUsage = historicalData.Average(d => d.MemoryUsage);
                    report.AverageGpuUsage = historicalData.Average(d => d.GpuUsage);

                    // 计算峰值
                    report.PeakCpuUsage = historicalData.Max(d => d.CpuUsage);
                    report.PeakMemoryUsage = historicalData.Max(d => d.MemoryUsage);
                    report.PeakGpuUsage = historicalData.Max(d => d.GpuUsage);

                    // 计算使用模式
                    report.UsagePatterns = AnalyzeUsagePatterns(historicalData);
                }

                return report;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取资源使用报告失败");
                return new ResourceUsageReport { Period = period };
            }
        }

        /// <summary>
        /// 调度任务
        /// </summary>
        public async Task<TaskSchedulingResult> ScheduleTaskAsync(ScheduledTask task)
        {
            try
            {
                var result = new TaskSchedulingResult
                {
                    TaskId = task.Id,
                    ScheduledAt = DateTime.Now
                };

                // 分析系统负载
                var currentMetrics = await GetCurrentPerformanceMetricsAsync();
                
                // 确定最佳执行时间
                var optimalTime = await DetermineOptimalExecutionTimeAsync(task, currentMetrics);
                task.ScheduledExecutionTime = optimalTime;

                // 添加到调度队列
                _scheduledTasks[task.Id] = task;

                // 设置执行定时器
                await SetupTaskExecutionTimerAsync(task);

                result.Success = true;
                result.OptimalExecutionTime = optimalTime;

                _logger.LogInformation($"任务已调度: {task.Id}, 执行时间: {optimalTime}");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"调度任务失败: {task.Id}");
                return new TaskSchedulingResult
                {
                    TaskId = task.Id,
                    Success = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取已调度任务
        /// </summary>
        public async Task<List<ScheduledTask>> GetScheduledTasksAsync()
        {
            try
            {
                return _scheduledTasks.Values.ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取已调度任务失败");
                return new List<ScheduledTask>();
            }
        }

        /// <summary>
        /// 取消调度任务
        /// </summary>
        public async Task<bool> CancelScheduledTaskAsync(string taskId)
        {
            try
            {
                if (_scheduledTasks.TryRemove(taskId, out var task))
                {
                    // 取消定时器
                    task.CancellationToken?.Cancel();
                    
                    _logger.LogInformation($"任务已取消: {taskId}");
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"取消调度任务失败: {taskId}");
                return false;
            }
        }

        /// <summary>
        /// 性能调优
        /// </summary>
        public async Task<PerformanceTuningResult> TunePerformanceAsync(PerformanceTuningRequest request)
        {
            try
            {
                var result = new PerformanceTuningResult
                {
                    RequestId = request.Id,
                    StartTime = DateTime.Now
                };

                var beforeMetrics = await GetCurrentPerformanceMetricsAsync();

                // 应用调优策略
                var appliedOptimizations = new List<string>();

                foreach (var strategy in request.TuningStrategies)
                {
                    var success = await ApplyTuningStrategyAsync(strategy);
                    if (success)
                    {
                        appliedOptimizations.Add(strategy);
                    }
                }

                // 等待调优生效
                await Task.Delay(TimeSpan.FromSeconds(30));

                var afterMetrics = await GetCurrentPerformanceMetricsAsync();

                // 计算改进效果
                result.PerformanceImprovement = CalculatePerformanceImprovement(beforeMetrics, afterMetrics);
                result.AppliedOptimizations = appliedOptimizations;
                result.Success = appliedOptimizations.Any();
                result.EndTime = DateTime.Now;

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "性能调优失败");
                return new PerformanceTuningResult
                {
                    RequestId = request.Id,
                    Success = false,
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 开始性能监控
        /// </summary>
        public async Task StartPerformanceMonitoringAsync()
        {
            try
            {
                if (_isMonitoring)
                    return;

                _isMonitoring = true;
                
                // 启动监控定时器
                var timer = new Timer(async _ => await CollectPerformanceMetricsAsync(), 
                    null, TimeSpan.Zero, TimeSpan.FromMinutes(1));

                _logger.LogInformation("性能监控已启动");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动性能监控失败");
            }
        }

        /// <summary>
        /// 停止性能监控
        /// </summary>
        public async Task StopPerformanceMonitoringAsync()
        {
            try
            {
                _isMonitoring = false;
                _monitoringTimer?.Dispose();
                
                _logger.LogInformation("性能监控已停止");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止性能监控失败");
            }
        }

        #region 私有辅助方法

        private async Task<Dictionary<string, object>> GetApplicationMetricsAsync()
        {
            var metrics = new Dictionary<string, object>();

            try
            {
                var process = Process.GetCurrentProcess();
                
                metrics["WorkingSet"] = process.WorkingSet64;
                metrics["PrivateMemorySize"] = process.PrivateMemorySize64;
                metrics["VirtualMemorySize"] = process.VirtualMemorySize64;
                metrics["ThreadCount"] = process.Threads.Count;
                metrics["HandleCount"] = process.HandleCount;
                metrics["TotalProcessorTime"] = process.TotalProcessorTime.TotalMilliseconds;

                // GC信息
                metrics["Gen0Collections"] = GC.CollectionCount(0);
                metrics["Gen1Collections"] = GC.CollectionCount(1);
                metrics["Gen2Collections"] = GC.CollectionCount(2);
                metrics["TotalMemory"] = GC.GetTotalMemory(false);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取应用程序指标失败");
            }

            return metrics;
        }

        private float CalculatePerformanceScore(SystemPerformanceMetrics metrics)
        {
            // 简化的性能评分算法
            var cpuScore = Math.Max(0, 100 - metrics.CpuUsage) / 100f;
            var memoryScore = Math.Max(0, 100 - metrics.MemoryUsage) / 100f;
            var diskScore = Math.Max(0, 100 - metrics.DiskUsage) / 100f;

            return (cpuScore + memoryScore + diskScore) / 3f;
        }

        private async Task<List<PerformanceMetricSnapshot>> GetHistoricalPerformanceDataAsync(TimeSpan period)
        {
            // 从存储中获取历史数据
            var data = new List<PerformanceMetricSnapshot>();
            
            // 从内存队列中获取最近的数据
            var cutoff = DateTime.Now.Subtract(period);
            data.AddRange(_metricsHistory.Where(m => m.Timestamp > cutoff));

            return data;
        }

        private PerformanceTrends AnalyzePerformanceTrends(List<PerformanceMetricSnapshot> historicalData)
        {
            if (!historicalData.Any())
                return new PerformanceTrends();

            var trends = new PerformanceTrends();
            
            // 计算趋势
            var sortedData = historicalData.OrderBy(d => d.Timestamp).ToList();
            
            if (sortedData.Count > 1)
            {
                var first = sortedData.First();
                var last = sortedData.Last();
                
                trends.CpuTrend = last.CpuUsage - first.CpuUsage;
                trends.MemoryTrend = last.MemoryUsage - first.MemoryUsage;
                trends.GpuTrend = last.GpuUsage - first.GpuUsage;
            }

            return trends;
        }

        private async Task<List<OptimizationSuggestion>> GenerateOptimizationSuggestionsAsync(
            SystemPerformanceMetrics currentMetrics, PerformanceTrends trends)
        {
            var suggestions = new List<OptimizationSuggestion>();

            // 基于当前指标生成建议
            if (currentMetrics.MemoryUsage > 80)
            {
                suggestions.Add(new OptimizationSuggestion
                {
                    Id = "memory_cleanup",
                    Title = "内存清理",
                    Description = "清理未使用的内存和缓存",
                    Priority = OptimizationPriority.High,
                    EstimatedImpact = "可释放10-20%内存"
                });
            }

            if (currentMetrics.CpuUsage > 85)
            {
                suggestions.Add(new OptimizationSuggestion
                {
                    Id = "task_scheduling",
                    Title = "任务调度优化",
                    Description = "优化任务执行时间和并发度",
                    Priority = OptimizationPriority.Medium,
                    EstimatedImpact = "可降低15-25% CPU使用率"
                });
            }

            return suggestions;
        }

        private async Task<Dictionary<string, float>> EstimateOptimizationImpactAsync(List<OptimizationSuggestion> suggestions)
        {
            var impact = new Dictionary<string, float>();
            
            foreach (var suggestion in suggestions)
            {
                // 基于历史数据估算影响
                impact[suggestion.Id] = await EstimateSingleOptimizationImpactAsync(suggestion);
            }

            return impact;
        }

        private async Task<float> EstimateSingleOptimizationImpactAsync(OptimizationSuggestion suggestion)
        {
            // 简化的影响估算
            return suggestion.Priority switch
            {
                OptimizationPriority.High => 0.8f,
                OptimizationPriority.Medium => 0.6f,
                OptimizationPriority.Low => 0.3f,
                _ => 0.5f
            };
        }

        private async Task<bool> PerformMemoryCleanupAsync()
        {
            try
            {
                // 强制垃圾回收
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                // 清理应用程序缓存
                // 这里可以添加具体的缓存清理逻辑

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "内存清理失败");
                return false;
            }
        }

        private async Task<bool> OptimizeCacheAsync()
        {
            // 缓存优化逻辑
            await Task.Delay(100);
            return true;
        }

        private async Task<bool> OptimizeTaskSchedulingAsync()
        {
            // 任务调度优化逻辑
            await Task.Delay(100);
            return true;
        }

        private async Task<bool> OptimizeResourceAllocationAsync()
        {
            // 资源分配优化逻辑
            await Task.Delay(100);
            return true;
        }

        private Dictionary<string, object> AnalyzeUsagePatterns(List<PerformanceMetricSnapshot> data)
        {
            var patterns = new Dictionary<string, object>();

            if (data.Any())
            {
                // 分析使用模式
                var hourlyUsage = data.GroupBy(d => d.Timestamp.Hour)
                    .ToDictionary(g => g.Key.ToString(), g => g.Average(d => d.CpuUsage));

                patterns["HourlyUsage"] = hourlyUsage;
                patterns["PeakHour"] = hourlyUsage.OrderByDescending(kvp => kvp.Value).First().Key;
            }

            return patterns;
        }

        private async Task<DateTime> DetermineOptimalExecutionTimeAsync(ScheduledTask task, SystemPerformanceMetrics currentMetrics)
        {
            // 简化的最佳执行时间算法
            var baseTime = DateTime.Now;

            // 如果当前系统负载高，延迟执行
            if (currentMetrics.CpuUsage > 80 || currentMetrics.MemoryUsage > 80)
            {
                baseTime = baseTime.AddMinutes(30);
            }

            // 根据任务优先级调整
            switch (task.Priority)
            {
                case TaskPriority.High:
                    return baseTime.AddMinutes(5);
                case TaskPriority.Medium:
                    return baseTime.AddMinutes(15);
                case TaskPriority.Low:
                    return baseTime.AddHours(1);
                default:
                    return baseTime.AddMinutes(10);
            }
        }

        private async Task SetupTaskExecutionTimerAsync(ScheduledTask task)
        {
            var delay = task.ScheduledExecutionTime - DateTime.Now;
            if (delay > TimeSpan.Zero)
            {
                task.CancellationToken = new CancellationTokenSource();
                
                _ = Task.Delay(delay, task.CancellationToken.Token).ContinueWith(async _ =>
                {
                    if (!task.CancellationToken.Token.IsCancellationRequested)
                    {
                        await ExecuteScheduledTaskAsync(task);
                    }
                });
            }
        }

        private async Task ExecuteScheduledTaskAsync(ScheduledTask task)
        {
            try
            {
                _logger.LogInformation($"执行调度任务: {task.Id}");
                
                task.Status = TaskStatus.Running;
                task.StartTime = DateTime.Now;

                // 执行任务逻辑
                await task.ExecuteAsync();

                task.Status = TaskStatus.Completed;
                task.EndTime = DateTime.Now;

                // 从调度队列中移除
                _scheduledTasks.TryRemove(task.Id, out _);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"执行调度任务失败: {task.Id}");
                task.Status = TaskStatus.Failed;
                task.ErrorMessage = ex.Message;
            }
        }

        private async Task<bool> ApplyTuningStrategyAsync(string strategy)
        {
            return strategy switch
            {
                "memory_optimization" => await PerformMemoryCleanupAsync(),
                "cpu_optimization" => await OptimizeTaskSchedulingAsync(),
                "cache_optimization" => await OptimizeCacheAsync(),
                "resource_optimization" => await OptimizeResourceAllocationAsync(),
                _ => false
            };
        }

        private PerformanceImprovement CalculatePerformanceImprovement(
            SystemPerformanceMetrics before, SystemPerformanceMetrics after)
        {
            return new PerformanceImprovement
            {
                CpuImprovement = before.CpuUsage - after.CpuUsage,
                MemoryImprovement = before.MemoryUsage - after.MemoryUsage,
                GpuImprovement = before.GpuUsage - after.GpuUsage,
                OverallImprovement = (before.PerformanceScore - after.PerformanceScore) * 100
            };
        }

        private async Task CollectPerformanceMetricsAsync()
        {
            try
            {
                if (!_isMonitoring)
                    return;

                var metrics = await GetCurrentPerformanceMetricsAsync();
                var snapshot = new PerformanceMetricSnapshot
                {
                    Timestamp = metrics.Timestamp,
                    CpuUsage = metrics.CpuUsage,
                    MemoryUsage = metrics.MemoryUsage,
                    GpuUsage = metrics.GpuUsage,
                    DiskUsage = metrics.DiskUsage,
                    NetworkUsage = metrics.NetworkUsage
                };

                _metricsHistory.Enqueue(snapshot);

                // 保持最近1000个数据点
                while (_metricsHistory.Count > 1000)
                {
                    _metricsHistory.TryDequeue(out _);
                }

                // 定期保存到存储
                if (_metricsHistory.Count % 60 == 0) // 每小时保存一次
                {
                    await SaveMetricsToStorageAsync();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "收集性能指标失败");
            }
        }

        private async Task SaveMetricsToStorageAsync()
        {
            try
            {
                var data = _metricsHistory.ToList();
                var key = $"performance_metrics_{DateTime.Now:yyyyMMdd_HH}";
                await _dataStorage.SaveAsync(key, data);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存性能指标失败");
            }
        }

        #endregion
    }
}
